// VNC调试脚本
import axios from 'axios';

const API_BASE = 'http://localhost:8080/api/v1';

async function debugVNC() {
  try {
    console.log('=== VNC调试信息 ===');

    // 1. 获取虚拟机列表
    console.log('\n1. 获取虚拟机列表...');
    const domainsResponse = await axios.get(`${API_BASE}/domains?inactive=true`);
    const domains = domainsResponse.data.domains;
    console.log(`找到 ${domains.length} 个虚拟机`);

    if (domains.length === 0) {
      console.log('没有虚拟机，无法测试VNC功能');
      return;
    }

    // 2. 检查第一个虚拟机的VNC信息
    const testDomain = domains[0];
    console.log(`\n2. 检查虚拟机 "${testDomain.name}" 的VNC信息...`);

    try {
      const vncResponse = await axios.get(`${API_BASE}/domains/${testDomain.name}/vnc`);
      const vncInfo = vncResponse.data;

      console.log('VNC信息:');
      console.log('- Host:', vncInfo.host);
      console.log('- Port:', vncInfo.port);
      console.log('- WebSocket Port:', vncInfo.websocket_port);
      console.log('- Password:', vncInfo.password ? '有密码' : '无密码');
      console.log('- Console WebSocket URL:', vncInfo.console_websocket_url);

      // 3. 检查端口有效性
      console.log('\n3. 端口分析:');
      if (vncInfo.port === -1) {
        console.log('- VNC端口为-1，表示需要自动分配');
      } else if (vncInfo.port >= 5900 && vncInfo.port <= 5999) {
        console.log('- VNC端口在有效范围内 (5900-5999)');
      } else {
        console.log('- VNC端口可能有问题:', vncInfo.port);
      }

      // 4. 生成连接信息
      console.log('\n4. 连接信息:');
      const vncPort = vncInfo.port === -1 ? '自动分配' : vncInfo.port;
      const wsPort = vncInfo.websocket_port || (vncInfo.port - 5900 + 6900);
      console.log('- VNC连接:', `${vncInfo.host}:${vncPort}`);
      console.log('- WebSocket连接:', `ws://${vncInfo.host}:${wsPort}/websockify`);

    } catch (vncError) {
      console.log('获取VNC信息失败:', vncError.response?.data || vncError.message);
    }

    // 5. 获取虚拟机详细信息
    console.log('\n5. 获取虚拟机详细信息...');
    try {
      const detailResponse = await axios.get(`${API_BASE}/domains/${testDomain.name}`);
      const domainDetail = detailResponse.data.domain;
      console.log('虚拟机状态:', domainDetail.state);

      // 检查XML中是否有VNC配置
      if (domainDetail.xml) {
        const hasVNC = domainDetail.xml.includes('vnc');
        console.log('XML中包含VNC配置:', hasVNC);

        if (hasVNC) {
          // 提取VNC端口信息
          const vncMatch = domainDetail.xml.match(/vnc.*port=['"](\d+)['"]/);
          if (vncMatch) {
            console.log('XML中VNC端口:', vncMatch[1]);
          }
        }
      }

    } catch (detailError) {
      console.log('获取详细信息失败:', detailError.response?.data || detailError.message);
    }

  } catch (error) {
    console.error('调试失败:', error.message);
    if (error.code === 'ECONNREFUSED') {
      console.log('无法连接到后端API服务器，请确保服务器运行在 http://localhost:8080');
    }
  }
}

// 运行调试
debugVNC();